package com.stedu.mall.orderservice.aspect;

import com.stedu.mall.common.bean.Log;
import com.stedu.mall.common.service.LogService;
import com.stedu.mall.common.utils.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@Component
@Aspect
public class SysAspect {
    @Autowired
    private LogService logService;
//切入点 -- 对哪些方法进行增强
    @Pointcut("@annotation(com.situ.mall.orderservice.annotation.Log)")
    public void pt1(){
    
    }
    //增强方法
    @Around("pt1()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        //通过工具类获取request对象
        RequestAttributes reqa = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) reqa;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("token");
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        //获取url
        String url = request.getRequestURI().toString();
        String methodName = request.getMethod();
        String ipAddr = request.getRemoteAddr();
        Date createTime = new Date();
        //新建一个对象，把值传进去
        Log log = new Log(url, methodName, ipAddr, createTime);
        //调用service
        logService.insert(log);
        return joinPoint.proceed();
    }
}
